<template>
  <el-dialog v-model="dialogVisible" :title="title" width="500px" @close="handleClose">
    <div class="import-dialog">
      <div class="import-tips">
        <div class="tip-item">
          <span>请先下载导入模板，按模板格式填写数据</span>
        </div>
        <div class="tip-item">
          <span>支持的文件格式：{{ fileTypes.join('、') }}</span>
        </div>
      </div>

      <div class="download-template"></div>

      <el-upload
        ref="uploadRef"
        :accept="acceptTypes"
        action="#"
        :auto-upload="false"
        :before-upload="beforeUpload"
        class="upload-area"
        :limit="1"
        :on-change="handleFileChange"
        :show-file-list="true"
      >
        <el-button type="primary">
          <upload class="mr-2" />
          选择文件
        </el-button>
      </el-upload>

      <div class="dialog-footer flex justify-between">
        <el-button :loading="downloadLoading" plain type="primary" @click="handleDownloadTemplate">
          <download v-if="!downloadLoading" class="mr-2" />
          下载导入模板
        </el-button>
        <div class="flex gap-2">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button :disabled="!hasFile || uploading" type="primary" @click="submitUpload">
            <loading v-if="uploading" class="mr-2" />
            {{ uploading ? '导入中...' : '开始导入' }}
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Download, Loading, Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, defineEmits, defineProps, ref } from 'vue'
import { importFile } from '/@/api/import-export'
import Public from '/@/api/public'

const baseURL = import.meta.env.VITE_APP_BASE_URL

const props = defineProps({
  title: {
    type: String,
    default: '批量导入',
  },
  importUrl: {
    type: String,
    required: true,
  },
  templateUrl: {
    type: String,
    default: '',
  },
  templateApiUrl: {
    type: String,
    default: '',
  },
  templateFileName: {
    type: String,
    default: '导入模板.xlsx',
  },
  fileTypes: {
    type: Array as () => string[],
    default: () => ['xlsx', 'xls'],
  },
  activityId: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['success', 'close'])

const dialogVisible = ref(false)
const uploadRef = ref()
const fileList = ref<Array<any>>([])
const hasFile = computed(() => fileList.value.length > 0)
const uploading = ref(false)
const downloadLoading = ref(false)

// 计算接受的文件类型
const acceptTypes = computed(() => {
  return props.fileTypes.map((type) => `.${type}`).join(',')
})

// 文件变更处理
const handleFileChange = (file: any, files: any[]) => {
  fileList.value = files
}

// 上传前验证
const beforeUpload = (file: any) => {
  const isValidType = props.fileTypes.some((type) => file.name.toLowerCase().endsWith(`.${type.toLowerCase()}`))

  if (!isValidType) {
    ElMessage.error(`请上传${props.fileTypes.join('或')}格式的文件`)
    return false
  }

  return true
}

// 提交上传
const submitUpload = async () => {
  if (!hasFile.value) {
    ElMessage.warning('请先选择要上传的文件')
    return
  }

  uploading.value = true
  try {
    const formData = new FormData()
    const file = fileList.value[0].raw
    formData.append('file', file)

    // 如果有activityId参数，需要添加到上传数据中
    if (props.activityId) {
      formData.append('activityId', props.activityId)
    }

    const response = await importFile(props.importUrl, formData)
    handleSuccess(response)
  } catch (error) {
    handleError(error)
  } finally {
    uploading.value = false
  }
}

// 下载导入模板
const handleDownloadTemplate = async () => {
  // 如果没有提供API地址，则使用旧的静态链接方式
  if (!props.templateApiUrl) {
    if (!props.templateUrl) {
      ElMessage.warning('未配置模板下载地址')
      return
    }
    window.open(`${baseURL}${props.templateUrl}`, '_blank')
    return
  }

  downloadLoading.value = true
  try {
    // 使用getDetailApi获取模板文件路径
    const response = await Public.getDetailApi({
      url: props.templateApiUrl,
    })

    // 类型断言，确保能够正确访问code和result属性
    const apiResponse = response as any
    if (apiResponse.code !== 0 || !apiResponse.result) {
      ElMessage.error(apiResponse.message || '获取模板文件失败')
      return
    }

    // 获取到文件路径后下载文件
    const fileUrl = apiResponse.result
    console.log('文件路径:', fileUrl)

    // 确保baseURL末尾有/，fileUrl开头没有/，避免双斜杠或缺少斜杠的问题
    let normalizedBaseURL = baseURL
    if (!normalizedBaseURL.endsWith('/')) {
      normalizedBaseURL = `${normalizedBaseURL}/`
    }

    let normalizedFileUrl = fileUrl
    if (normalizedFileUrl.startsWith('/')) {
      normalizedFileUrl = normalizedFileUrl.substring(1)
    }

    // 判断是否是完整的URL，如果不是则拼接baseURL
    const fullUrl = fileUrl.startsWith('http') ? fileUrl : `${normalizedBaseURL}${normalizedFileUrl}`

    console.log('完整下载URL:', fullUrl)

    // 方法一：使用window.open直接打开下载链接
    window.open(fullUrl, '_blank')

    ElMessage.success('模板下载中，请稍候...')
  } catch (error) {
    console.error('模板下载失败', error)
    ElMessage.error('模板下载失败，请稍后重试')
  } finally {
    downloadLoading.value = false
  }
}

// 上传成功
const handleSuccess = (response: any) => {
  if (response.code === 0) {
    ElMessage.success('导入成功')
    emit('success')
    dialogVisible.value = false
  } else {
    ElMessage.error(response.message || '导入失败')
  }
}

// 上传失败
const handleError = (error: any) => {
  console.error('导入失败', error)
  ElMessage.error('导入失败，请稍后重试')
}

// 关闭处理
const handleClose = () => {
  fileList.value = []
  emit('close')
}

// 对外暴露方法
const open = () => {
  dialogVisible.value = true
}

defineExpose({
  open,
})
</script>

<style scoped>
.import-dialog {
  padding: 0 20px;
}

.import-tips {
  margin-bottom: 20px;
}

.tip-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #e6a23c;
}

.icon {
  margin-right: 8px;
  color: #e6a23c;
}

.download-template {
  margin-bottom: 20px;
}

.download-link {
  text-decoration: none;
}

.upload-area {
  margin-bottom: 20px;
}

.dialog-footer {
  margin-top: 30px;
}

.mr-2 {
  margin-right: 8px;
}
</style>
